﻿
using BulletSharp;
using UnityEngine;
using System;
using System.IO;
using ETModel;

namespace ETHotfix {

    public static class UnitConfigHelper {
        public static Vector3 GetCenter(this UnitConfig self) {
            if (self.Center == null || self.Center.Length != 3) return Vector3.zero;
            return new Vector3(self.Center[0], self.Center[1], self.Center[2]);
        }
        public static Vector3 GetLocalScale(this UnitConfig self) {
            if (self.LocalScale == null || self.LocalScale.Length != 3) return Vector3.zero;
            return new Vector3(self.LocalScale[0], self.LocalScale[1], self.LocalScale[2]);
        }
        public static Vector3 GetBulletBoxRadius(this UnitConfig self) {
            if (self.BulletBoxRadius == null || self.BulletBoxRadius.Length != 3) return Vector3.zero;
            return new Vector3(self.BulletBoxRadius[0], self.BulletBoxRadius[1], self.BulletBoxRadius[2]);
        }
        public static Vector3 GetBulletLocalScale(this UnitConfig self) {
            if (self.BulletLocalScale == null || self.BulletLocalScale.Length != 3) return Vector3.one;
            return new Vector3(self.BulletLocalScale[0], self.BulletLocalScale[1], self.BulletLocalScale[2]);
        }
        public static CollisionShape CreateBulletCollisionShape(this UnitConfig self) {
            var eShape = Enum.Parse<BroadphaseNativeType>(self.BulletShapeType);
            switch (eShape) {
                case BroadphaseNativeType.BoxShape:
                    var boxRadius = self.GetBulletBoxRadius();
                    if (boxRadius == Vector3.zero) {
                        throw new Exception("该单位配置为方块物理形状,但未提供半径配置(BulletBoxRadius字段),或为0!");
                    }
                    return new BoxShape(boxRadius.x, boxRadius.y, boxRadius.z);
                case BroadphaseNativeType.TriangleMeshShape:
                    if (string.IsNullOrEmpty(self.BulletTriangleMeshFile)) {
                        throw new Exception("该单位配置为三角形网格物理形状,但未提供加载文件路径(BulletTriangleMeshFile字段)!");
                    }
                    if (!File.Exists(self.BulletTriangleMeshFile)) {
                        throw new Exception("该单位配置为三角形网格物理形状,但提供的加载文件路径不存在(BulletTriangleMeshFile字段)!");
                    }
                    var bulletLocalScale = self.GetBulletLocalScale();
                    return BulletHelper
                        .CreateMeshShapeFromObjFile(self.BulletTriangleMeshFile, bulletLocalScale.ToBullet());
                default:
                    throw new Exception("该单位的物理形状未实现构造!");
            }
        }
    }
}

